import * as THREE from 'three'
import createApp from '../../core'

function createMeshNormalMaterial (dom: HTMLElement) {
  const { camera, scene, gui } = createApp(dom)
  camera.position.set(-80, 60, 120)
  camera.lookAt(scene.position)

  const axes = new THREE.AxesHelper(100)
  scene.add(axes)

  const boxGeo = new THREE.BoxGeometry(30, 30, 30)
  const boxMaterial = new THREE.MeshNormalMaterial()
  const box = new THREE.Mesh(boxGeo, boxMaterial)
  box.position.z = -50
  scene.add(box)

  const sphereGeo = new THREE.SphereGeometry(15)
  const sphereMaterial = new THREE.MeshNormalMaterial()
  const sphere = new THREE.Mesh(sphereGeo, sphereMaterial)
  box.position.z = 50
  scene.add(sphere)

  const loader = new THREE.TextureLoader()

  gui.add(materialMap, 'normalMap').onChange(() => {
    if (materialMap.normalMap) {
      import('@/assets/material/alphaMap.png').then(image => {
        loader.load(image.default, texture => {
          boxMaterial.normalMap = texture
          boxMaterial.needsUpdate = true
          sphereMaterial.normalMap = texture
          sphereMaterial.needsUpdate = true
        })
      })
    } else {
      boxMaterial.normalMap = null
      boxMaterial.needsUpdate = true
      sphereMaterial.normalMap = null
      sphereMaterial.needsUpdate = true
    }
  })

  gui.add(materialMap, 'bumpMap').onChange(() => {
    if (materialMap.bumpMap) {
      // 凹凸材质
      import('@/assets/material/brick_roughness.png').then(image => {
        loader.load(image.default, texture => {
          boxMaterial.bumpMap = texture
          boxMaterial.needsUpdate = true
          sphereMaterial.bumpMap = texture
          sphereMaterial.needsUpdate = true
        })
      })
    } else {
      boxMaterial.bumpMap = null
      boxMaterial.needsUpdate = true
      sphereMaterial.bumpMap = null
      sphereMaterial.needsUpdate = true
    }
  })
}

const materialMap = {
  normalMap: false,
  bumpMap: false
}

export {
  createMeshNormalMaterial
}
